package com.bdqn.controller;

import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysUserService;
import com.bdqn.util.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * IndexController
 *
 * @author LILIBO
 * @since 2024/7/27
 */
@Controller
public class IndexController {

    /**
     * 引入业务逻辑层
     */
    @Resource
    private SysUserService sysUserService;

    /**
     * 去登录页
     */
    @GetMapping("/login")
    public String toLogin() {
        // 加载页面渲染需要的资源
        return "login";
    }

    /**
     * 执行登录操作
     */
    @PostMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session, @RequestParam("account") String account, @RequestParam("password") String password) {
        /*
        // 模拟发生异常
        if (password.equals("1234567")) {
            throw new RuntimeException("登录出现异常！");
        } */
        SysUser sysUser = sysUserService.login(account, password);
        if (sysUser == null) {
            // 验证失败，跳转到登录页
            request.setAttribute("error", "账号或密码错误，请重新登录");
            return "login";
        }
        // 将用户对象设置到Session作用域
        session.setAttribute(Constants.USER_SESSION, sysUser);
        // 跳转到主页
        return "redirect:/frame"; // redirect：重定向（让浏览器发起请求）
    }

    /**
     * 跳转到首页
     */
    @GetMapping("/frame")
    public String toFrame() {
        return "frame";
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(Constants.USER_SESSION);
        session.invalidate(); // 销毁Session
        return "redirect:/login";
    }

    /**
     * 局部异常处理（兜底）
     */
    // @ExceptionHandler(value = {RuntimeException.class})
    /* public String handlException(RuntimeException e, HttpServletRequest request) {
        request.setAttribute("e", e);
        return "error";
    } */

}
